package cn.lysj.framework.common.utils.websocket;


import cn.lysj.framework.common.annotation.CurrentUser;
import cn.lysj.framework.common.domain.User;
import cn.lysj.framework.common.utils.json.GsonUtil;
import cn.lysj.framework.common.utils.web.Resp;
import cn.lysj.framework.store.domain.CustEatTable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @Author: ZhangWenJian
 * @Create: 2018/7/21--16:17
 * @Description: WebSocket服务类
 */



@ServerEndpoint(value = "/websocket/store/{sid}")
@Component
public class WebSocketServerToStore {
    private  final static Logger log = LoggerFactory.getLogger(WebSocketServerToStore.class);
    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;
    //concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<WebSocketServerToStore> webSocketSet = new CopyOnWriteArraySet<WebSocketServerToStore>();

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;

    //接收sid
    private String sid="";
    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid) {
        this.session = session;
        webSocketSet.add(this);     //加入set中
        addOnlineCount();           //在线数加1
        log.info("有新窗口开始监听:"+sid+",当前在线人数为" + getOnlineCount());
        this.sid=sid;
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //从set中删除
        subOnlineCount();           //在线数减1
        log.info("有一连接关闭！当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("收到来自窗口"+sid+"的信息:"+message);
        //群发消息
        for (WebSocketServerToStore item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
        error.printStackTrace();
    }
    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }


    //给指定对象集合其中一个发送数据 1.服务类型 2.数据  3.前缀 4.是否完全遍历
    public static Integer sendDataToMorePeopleMap(Integer incidentType,Object data,String jointId,Boolean repeat){
        Integer peopleNum = 0;
//        红色为遍历对象
        for (WebSocketServerToStore item : webSocketSet) {
            try {
                if(item.sid.equals(jointId)){
                    WebSocketObj webSocketObj = new WebSocketObj();
                    webSocketObj.setIncidentType(incidentType);
                    webSocketObj.setData(data);
                    item.sendMessage(GsonUtil.toJson(new Resp(webSocketObj)));
                    peopleNum += 1;
                    if(!repeat){
                        break;
                    }
                }
            } catch (IOException e) {
                continue;
            }
        }
        return peopleNum;
    }


    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServerToStore.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServerToStore.onlineCount--;
    }

}
